package io.renren.modules.app.controller;

import com.baomidou.mybatisplus.mapper.Condition;
import io.renren.common.utils.R;
import io.renren.modules.generator.entity.KucunEntity;
import io.renren.modules.generator.service.ItemService;
import io.renren.modules.generator.service.KucunService;
import io.renren.modules.generator.vo.ItemWithStockVo;
import io.renren.modules.generator.vo.ListItemAndStockDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController("apiItemController")
@RequestMapping("/api")
@Api("物料信息接口")
public class ItemController {
    @Autowired
    private ItemService itemService;


    /**
     * 物料批次选择项
     *
     * @return
     */
    @PostMapping("listItems")
    @ApiOperation("list")
    public R listItems() {
        List<ListItemAndStockDTO> page = itemService.listItemStock();
        return R.ok().put("data", page);
    }


    @Autowired
    KucunService kucunService;

    @PostMapping("listItemsForCheck")
    @ApiOperation("listItemsForCheck")
    public R listItemsForCheck(@RequestParam Map<String, Object> params) {

        List<ItemWithStockVo> response = new ArrayList<>();

        List<ListItemAndStockDTO> page = itemService.listItemStock();

        List<String> itemGuids = page.stream().map(ListItemAndStockDTO::getGuid).collect(Collectors.toList());

        List<KucunEntity> kucuns = kucunService.selectList(Condition.create().in("item_guid", itemGuids));
        Map<String, KucunEntity> kucunMap = kucuns.stream().collect(Collectors.toMap(KucunEntity::getKey, body -> body));
        page.stream().forEach(x -> {
            ItemWithStockVo vo = new ItemWithStockVo();
            BeanUtils.copyProperties(x, vo);
            if (kucunMap.get(x.getGuid() + "-" + x.getBatchNo()) != null) {
                vo.setAmount(kucunMap.get(x.getGuid() + "-" + x.getBatchNo()).getAmount());
                vo.setVirAmount(kucunMap.get(x.getGuid() + "-" + x.getBatchNo()).getVirAmount());
                response.add(vo);
            }

        });
        return R.ok().put("data", response);
    }

}
